package ift585.tp3;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HtmlParserUtility {


	public static String[] parseTextContent(String contentToParse) {
		String[] resources = null;
		
		Pattern image = Pattern.compile("<img.[^>]+>", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
		Pattern css = Pattern.compile("<link.[^>]+>", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);

		Matcher imageMatcher = image.matcher(contentToParse);
		Matcher styleSheet = css.matcher(contentToParse);
		
		List<String> lines = new ArrayList<String>();

		while (imageMatcher.find()) {
			lines.add(imageMatcher.group());
		}
		
		while (styleSheet.find()){
			lines.add(styleSheet.group());
		}

		Pattern source = Pattern.compile("src=\".[^\"]+\"", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
		Pattern type = Pattern.compile("type=\".[^\"]+\"", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
		Pattern hrel = Pattern.compile("href=\".[^\"]+\"", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
		Matcher srcMatcher = null;
		Matcher typeMatcher = null;
		Matcher hrefMatcher = null;
		
		resources = new String[lines.size()];
		
		for (int i = 0; i < lines.size(); ++i){
			srcMatcher = source.matcher(lines.get(i));
			typeMatcher = type.matcher(lines.get(i));
			
			if(srcMatcher.find()){
				String trimURL = srcMatcher.group();
				resources[i] = trimURL.substring(trimURL.indexOf("\"")+1, trimURL.lastIndexOf("\""));
			}
			
			if(typeMatcher.find()){
				String trimType = typeMatcher.group();
				
				if(trimType.contains("text/css") || trimType.contains("image")){
					hrefMatcher = hrel.matcher(lines.get(i));
					
					if(hrefMatcher.find()){
						String trimHrel = hrefMatcher.group();
						resources[i] = trimHrel.substring(trimHrel.indexOf("\"")+1, trimHrel.lastIndexOf("\""));
					}
				}
			}
		}
		
		return resources;
	}

}
